package com.mt.baseinfo.aspect;

import com.mt.baseinfo.config.DynamicDataSourceContextHolder;
import com.mt.baseinfo.mult.DataSource;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;


@Aspect
@Order(1)
@Component
@Slf4j
public class DataSourceClassAspect {


    @Before("@annotation(dataSource)")
    public void doBefore(JoinPoint point, DataSource dataSource){
        log.info("切换到数据源[{}]", dataSource.value().name());
        DynamicDataSourceContextHolder.setDataSourceType(dataSource.value().name());
    }

    @After("@annotation(dataSource)")
    public void doAfter(JoinPoint point, DataSource dataSource){
        log.info("回收数据源[{}]", dataSource.value().name());
        DynamicDataSourceContextHolder.clearDataSourceType();
    }

   /* @Before("@within(dataSource)")
    public void doBefore(JoinPoint point, DataSource dataSource){
        log.info("切换到数据源[{}]", dataSource.value().getValue());
        DynamicDataSourceContextHolder.setDataSourceType(dataSource.value().getValue());
    }


    @Around("dsPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        DataSource dataSource = method.getAnnotation(DataSource.class);
        if (dataSource != null) {
            DynamicDataSourceContextHolder.setDataSourceType(dataSource.value().name());
        }
        try {
            return point.proceed();
        } finally {
            // 销毁数据源 在执行方法之后
            DynamicDataSourceContextHolder.clearDataSourceType();
        }
    }*/
}